import urllib
import requests
import os
import re

os.chdir(os.path.dirname(os.path.abspath(__file__)))

def parse_kodi_image_url(kodi_url):
    """解析Kodi格式的图片URL，返回实际的图片URL"""
    if kodi_url.startswith("image://"):
        kodi_url = kodi_url[8:]
    if kodi_url.endswith("/"):
        kodi_url = kodi_url[:-1]
    return urllib.parse.unquote(kodi_url)

def convert_to_cdn_url(original_url):
    """将原始URL转换为CDN加速URL，支持多个CDN源"""
    # 检查是否为TMDB原始URL
    tmdb_pattern = r"https://image\.tmdb\.org/t/p/([^/]+)/([^/]+)"
    match = re.search(tmdb_pattern, original_url)
    if match:
        size = match.group(1)
        image_id = match.group(2)
        return f"https://kodi-proxy.deno.dev/tmdb/t/p/{size}/{image_id}"
    
    # 新增：检查是否为melonhu CDN URL
    melonhu_pattern = r"https://tmdb\.melonhu\.cn/img/t/p/([^/]+)/([^/]+)"
    match = re.search(melonhu_pattern, original_url)
    if match:
        size = match.group(1)
        image_id = match.group(2)
        return f"https://kodi-proxy.deno.dev/tmdb/t/p/{size}/{image_id}"
    
    # 不匹配任何已知CDN模式，返回原始URL
    return original_url

def download_and_save_image(url, filename, output_dir="."):
    """下载图片并保存到指定目录"""
    try:
        os.makedirs(output_dir, exist_ok=True)
        file_path = os.path.join(output_dir, filename)
        cdn_url = convert_to_cdn_url(url)
        print(f"下载图片: {cdn_url} -> {file_path}")
        response = requests.get(cdn_url, timeout=10)
        response.raise_for_status()
        with open(file_path, 'wb') as f:
            f.write(response.content)
        print(f"✅ 图片已保存: {file_path}")
        return True
    except Exception as e:
        print(f"❌ 下载失败: {str(e)}")
        return False

def extract_and_save_posters(media_items, output_dir="posters"):
    """从媒体项目列表中提取并保存海报图片"""
    success_count = 0
    for i, item in enumerate(media_items):
        title = item.get("title", f"media_{i}")
        art = item.get("art", {})
        poster_url = art.get("poster")
        if not poster_url:
            print(f"⚠️ 未找到海报: {title}")
            continue
        actual_url = parse_kodi_image_url(poster_url)
        safe_title = re.sub(r'[\\/*?:"<>|]', "", title)
        ext = os.path.splitext(actual_url)[1] or ".jpg"
        filename = f"{safe_title}{ext}"
        if download_and_save_image(actual_url, filename, output_dir):
            success_count += 1
    return success_count
